package indexv1

import (
	"encoding/json"
	"lingc/config"
	"lingc/services"
	"lingc/utils"
	"log"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

// 导入 common 包
// 获取配置信息
func GetSysConfigData(c *gin.Context) {
	// 获取语言翻译列表
	sysConfig, err := services.NewSysConfigService(utils.MysqlClient).GetSysConfigData(c)
	if err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
		return
	}
	sysConfig["lang_cahce_time"] = services.NewSysLangDetailService(utils.MysqlClient).GetCahceConfigTime(c)
	utils.SendJSONResponse(c, utils.SuccessCode, gin.H{"config": sysConfig})
}

// 上传图片
func UploadImage(c *gin.Context) {
	// 获取上传的文件
	file, err := c.FormFile("file")
	if err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
		return
	}
	// 获取文件名
	filename := utils.GenerateMD5(file.Filename) + "." + strings.Split(file.Filename, ".")[1]

	// 获取当前日期
	currentDate := time.Now().Format("20060102")
	// 创建日期文件夹
	uploadPath := "./uploads/" + currentDate
	if err := os.MkdirAll(uploadPath, os.ModePerm); err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Failed to create directory"})
		return
	}

	// 保存文件到服务器
	dst := uploadPath + "/" + filename
	err1 := c.SaveUploadedFile(file, dst)
	if err1 != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err1.Error()})
		return
	}

	fileReader, err := file.Open()
	if err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Failed to open file"})
		return
	}
	defer fileReader.Close()

	err2 := utils.UploadToOSS(fileReader, "uploads/"+currentDate+"/"+filename)
	if err2 != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err2.Error()})
		return
	}
	url := config.BaseURL + "/uploads/" + currentDate + "/" + filename
	utils.SendJSONResponse(c, utils.SuccessCode, gin.H{"name": filename, "url": url})
}

// 删除文件
func DeleteImage(c *gin.Context) {
	filename := c.Query("filename")
	if filename == "" {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "filename is required"})
		return
	}
	filename = strings.Replace(filename, config.BaseURL, "", 1)
	// 删除文件
	err := os.Remove("." + filename)
	if err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
	}
	utils.SendJSONResponse(c, utils.SuccessCode, gin.H{"msg": "文件已删除"})
}

// 获取语言翻译列表
func GetLangList(c *gin.Context) {
	langList, err := services.NewSysLangDetailService(utils.MysqlClient).GetSysLangList(false)
	if err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
		return
	}
	lang_map_list := make(map[string]interface{})
	json.Unmarshal([]byte(langList), &lang_map_list)
	log.Printf("lang_map_list：%v", lang_map_list)
	utils.SendJSONResponse(c, utils.SuccessCode, gin.H{"lang_list": lang_map_list})
}

// 获取聊天记录列表
func GetChatHistoryList(c *gin.Context) {
	userInterface, exists := c.Get("user")
	if !exists {
		utils.SendJSONResponse(c, utils.ErrorToken, gin.H{"msg": "用户未找到"})
		return
	}
	user, ok := userInterface.(*utils.Claims) // 假设 utils.User 是 user 的类型
	if !ok {
		utils.SendJSONResponse(c, utils.ErrorToken, gin.H{"msg": "用户类型失败"})
		return
	}
	group_id, _ := strconv.Atoi(c.Query("group_id"))
	where := "group_id = " + c.Query("group_id")
	relation, _ := services.NewChatService(utils.MysqlClient).GetChatGroupRelationById(uint(group_id), user.ID, user.Type)
	if relation == nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "用户未加入该群组"})
		return
	}
	page, _ := strconv.Atoi(c.Query("page"))
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	list, total, err := services.NewChatService(utils.MysqlClient).GetChatHistoryList(where, page, pageSize)
	if err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
		return
	}
	utils.SendJSONResponse(c, utils.SuccessCode, gin.H{"list": list, "total": total})
}
